package com.yenlien.traceyun.plant.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.service.rest.usercenter.FileRestService;
import com.yenlien.traceyun.plant.dao.PlantDao;
import com.yenlien.traceyun.plant.dao.ReapDao;
import com.yenlien.traceyun.plant.dao.ReapDetailDao;
import com.yenlien.traceyun.plant.entity.Plant;
import com.yenlien.traceyun.plant.entity.Reap;
import com.yenlien.traceyun.plant.entity.ReapDetail;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReapService {
    @Autowired
    private PlantDao plantDao;
    @Autowired
    private ReapDao reapDao;
    @Autowired
    private ReapDetailDao reapDetailDao;
    @Autowired
    private FileRestService fileService;
    @Autowired
    private JdbcTemplate jdbc;


    public JSONObject findByList(JSONObject params) {
        JSONObject json = new JSONObject();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        int page = params.getIntValue("page");
        String soilName = params.getString("searchName");
        String reapName = params.getString("searchName");
        String jyName = params.getString("jyName");
        String companyId = params.getString("companyId");

        StringBuffer sql = new StringBuffer();
        sql.append("select r.id,d.reap_name,d.reap_part,r.batch,r.plant_base_name,r.reap_area,d.reap_number,d.units,r.begin_time,r.soil_name from t_plant_reap r left join t_plant_reap_detail d on r.id = d.reap_id where 1 = 1");
        //根据地块查询
        if (StringUtils.isNotEmpty(soilName)) {
            sql.append(" and (r.soil_name like '%" + soilName + "%' or d.reap_name like '%" + reapName + "%')");
        }
        if (StringUtils.isNotEmpty(companyId)) {
            sql.append(" and (r.company_id ='" + companyId + "')");
        }
        if (StringUtils.isNotEmpty(jyName)) {
            sql.append(" and (r.jy_name ='" + jyName + "')");
        }
        sql.append(" order by r.createtime desc");
        sql.append(" limit " + (page - 1) * 10 + ",10");
        SqlRowSet rowSet = jdbc.queryForRowSet(sql.toString());
        while (rowSet.next()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", rowSet.getString("id"));
            jsonObject.put("reapName", rowSet.getString("reap_name"));
            jsonObject.put("reapPart", rowSet.getString("reap_part"));
            jsonObject.put("batch", rowSet.getString("batch"));
            jsonObject.put("plantBaseName", rowSet.getString("plant_base_name"));
            jsonObject.put("reapArea", rowSet.getString("reap_area"));
            jsonObject.put("reapNumber", rowSet.getString("reap_number"));
            jsonObject.put("units", rowSet.getString("units"));
            jsonObject.put("beginTime", rowSet.getString("begin_time"));
            jsonObject.put("soilName", rowSet.getString("soil_name"));
            jsonObjectList.add(jsonObject);
        }

        StringBuffer sql1 = new StringBuffer();
        sql1.append("select count(1) from t_plant_reap r left join t_plant_reap_detail d on r.id = d.reap_id where 1 = 1");
        if (StringUtils.isNotEmpty(soilName)) {
            sql1.append(" and (r.soil_name like '%" + soilName + "%' or d.reap_name like '%" + reapName + "%')");
        }
        if (StringUtils.isNotEmpty(companyId)) {
            sql1.append(" and (r.company_id ='" + companyId + "')");
        }
        if (StringUtils.isNotEmpty(jyName)) {
            sql1.append(" and (r.jy_name ='" + jyName + "')");
        }
        SqlRowSet rowSet1 = jdbc.queryForRowSet(sql1.toString());
        int number = 0;
        while (rowSet1.next()) {
            number = rowSet1.getInt("count(1)");
        }
        json.put("code", "200");
        json.put("total", number);
        json.put("rows", jsonObjectList);

        return json;
    }



    public Object getSoilJY(String companyId) {
        List<Reap> reapList = reapDao.findByCompanyId(companyId);
        Map<String, List<Reap>> jyNameList = reapList.stream().collect(Collectors.groupingBy(Reap::getJyName));
        Map<String, List<Reap>> soilNameList = reapList.stream().collect(Collectors.groupingBy(Reap::getSoilName));
        JSONObject object = new JSONObject();
        object.put("jyNameList", jyNameList.keySet());
        object.put("soilNameList", soilNameList.keySet());
        return object;
    }


    public JSONObject findByListApp(JSONObject params) {
        JSONObject json = new JSONObject();
        List<JSONObject> jsonObjectList = new ArrayList<>();
        int page = params.getIntValue("page");
        String soilName = params.getString("soilName");
        String reapName = params.getString("reapName");
        String reapUserName = params.getString("reapUserName");
        String jyName = params.getString("jyName");
        String companyId = params.getString("companyId");

        StringBuffer sql = new StringBuffer();
        sql.append("select r.reap_user_name, d.reap_img, r.plant_img,r.id,d.reap_name,d.reap_part,r.batch,r.plant_base_name,r.reap_area,d.reap_number,d.units,r.begin_time,r.soil_name from t_plant_reap r left join " +
                "t_plant_reap_detail d on r.id = d.reap_id left join t_plant tp on tp.batch = r.plant_batch where 1 = 1");
        //根据地块查询
        if (StringUtils.isNotEmpty(reapUserName)) {
            sql.append(" and (r.reap_user_name like '%" + reapUserName + "%')");
        }
        if (StringUtils.isNotEmpty(soilName)) {
            sql.append(" and (r.soil_name like '%" + soilName + "%')");
        }
        if (StringUtils.isNotEmpty(companyId)) {
            sql.append(" and (r.company_id ='" + companyId + "')");
        }
        if (StringUtils.isNotEmpty(jyName)) {
            sql.append(" and (r.jy_name ='" + jyName + "')");
        }
//        if (reapStatus == 0) {
//            sql.append(" and (tp.reap_status = 0 or tp.reap_status = 1)");
//        }
//        if (reapStatus == 2) {
//            sql.append(" and (tp.reap_status = 2)");
//        }
        sql.append(" order by r.createtime desc");
        sql.append(" limit " + (page - 1) * 10 + ",10");
        SqlRowSet rowSet = jdbc.queryForRowSet(sql.toString());
        while (rowSet.next()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", rowSet.getString("id"));
            jsonObject.put("reapImg", rowSet.getString("reap_img"));
            jsonObject.put("reapUserName", rowSet.getString("reap_user_name"));
            jsonObject.put("plantImg", rowSet.getString("plant_img"));
            jsonObject.put("reapName", rowSet.getString("reap_name"));
            jsonObject.put("reapPart", rowSet.getString("reap_part"));
            jsonObject.put("batch", rowSet.getString("batch"));
            jsonObject.put("plantBaseName", rowSet.getString("plant_base_name"));
            jsonObject.put("reapArea", rowSet.getString("reap_area"));
            jsonObject.put("reapNumber", rowSet.getString("reap_number"));
            jsonObject.put("units", rowSet.getString("units"));
            jsonObject.put("beginTime", rowSet.getString("begin_time"));
            jsonObject.put("soilName", rowSet.getString("soil_name"));
            jsonObjectList.add(jsonObject);
        }

        StringBuffer sql1 = new StringBuffer();
        sql1.append("select count(1) from t_plant_reap r left join t_plant_reap_detail d on r.id = d.reap_id left join t_plant tp on tp.batch = r.plant_batch where 1 = 1");
        if (StringUtils.isNotEmpty(soilName)) {
            sql1.append(" and (r.soil_name like '%" + soilName + "%')");
        }
        if (StringUtils.isNotEmpty(companyId)) {
            sql1.append(" and (r.company_id ='" + companyId + "')");
        }
        if (StringUtils.isNotEmpty(reapUserName)) {
            sql1.append(" and (r.reap_user_name like '%" + reapUserName + "%')");
        }
        if (StringUtils.isNotEmpty(jyName)) {
            sql1.append(" and (r.jy_name ='" + jyName + "')");
        }
//        if (reapStatus == 0) {
//            sql1.append(" and (tp.reap_status = 0 or tp.reap_status = 1)");
//        }
//        if (reapStatus == 2) {
//            sql1.append(" and (tp.reap_status = 2)");
//        }
        SqlRowSet rowSet1 = jdbc.queryForRowSet(sql1.toString());
        int number = 0;
        while (rowSet1.next()) {
            number = rowSet1.getInt("count(1)");
        }
        json.put("code", "200");
        json.put("total", number);
        json.put("rows", jsonObjectList);

        return json;
    }

    public Reap findById(String id) {
        Reap reap = reapDao.findById(id);
        reap.setList(reapDetailDao.findByReapId(id));
        return reap;
    }

    public Reap getById(String id) {
        Reap reap = reapDao.findById(id);
        reap.setReapDetail(reapDetailDao.getByReapId(id));
        return reap;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public void save(Reap reap, List<MultipartFile> files) throws Exception {
        Plant plant = plantDao.findByBatch(reap.getPlantBatch());
        plant.setReapStatus(reap.getReapStatus());
        plantDao.save(plant);

        reap.setLastStep(plant.getId());
        reap.setPlantImg(plant.getPlantImg());
        reapDao.save(reap);
        List<ReapDetail> list = new ArrayList<>();
        JSONArray array = JSONArray.parseArray(reap.getReapDetailList());
        if (array != null) {
            list = JSONObject.parseArray(array.toJSONString(), ReapDetail.class);
        }
        //收获列表
        for (int i = 0; i < list.size(); i++) {
            ReapDetail reapDetail = list.get(i);
            MultipartFile file = getImage(reapDetail.getReapImg(), files);
            if (file != null) {
                List<MultipartFile> multipartFiles = new ArrayList<>();
                multipartFiles.add(files.get(i));
                fileService.upload(null, reapDetail, multipartFiles);
            }
            reapDetail.setBatch(reap.getBatch());
            reapDetail.setReapId(reap.getId());
            reapDetail.setSoilName(reap.getSoilName());
            reapDetail.setSurplusNumber(reapDetail.getReapNumber());
            reapDetail.setLastStep(reap.getId());
        }
        reapDetailDao.saveAll(list);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public void save2(Reap reap) throws Exception {
        Plant plant = plantDao.findByBatch(reap.getPlantBatch());
        plant.setReapStatus(reap.getReapStatus());
        plantDao.save(plant);

        reap.setLastStep(plant.getId());
        reap.setPlantImg(plant.getPlantImg());
        reapDao.save(reap);
        List<ReapDetail> list = new ArrayList<>();
        JSONArray array = JSONArray.parseArray(reap.getReapDetailList());
        if (array != null) {
            list = JSONObject.parseArray(array.toJSONString(), ReapDetail.class);
        }
        // 一个采收只对应一个详情
            ReapDetail reapDetail = list.get(0);
            reapDetail.setBatch(reap.getBatch());
            reapDetail.setReapId(reap.getId());
            reapDetail.setSoilName(reap.getSoilName());
            reapDetail.setSurplusNumber(reapDetail.getReapNumber());
            reapDetail.setLastStep(reap.getId());
        reapDetailDao.saveAll(list);
    }

    /**
     * 获取匹配的图片
     *
     * @param filename
     * @param files
     * @return
     */
    private MultipartFile getImage(String filename, List<MultipartFile> files) {
        if (files != null && files.size() > 0) {
            for (MultipartFile multipartFile : files) {
                if (multipartFile.getOriginalFilename().equals(filename)) {
                    return multipartFile;
                }
            }
        }
        return null;
    }

    public Object plantBatch(String plantBatch) {
        List<Reap> byPlantBatch = reapDao.findByPlantBatch(plantBatch);
        float i = 0;
        for (Reap reap : byPlantBatch) {
            List<ReapDetail> byReapId = reapDetailDao.findByReapId(reap.getId());
            for (ReapDetail reapDetail : byReapId) {
                i = i + Float.parseFloat(reapDetail.getReapNumber());
            }

        }
        List<String> strings = new ArrayList<>();
        strings.add(String.valueOf(byPlantBatch.size()));
        strings.add(String.valueOf(i));
        return strings;
    }

    //采购数量统计
    public BigDecimal purchaseCount(String companyId) {
        List<Map<String, Object>> li = reapDao.purchaseCount2(companyId);
        BigDecimal totalNum = new BigDecimal("0.00");
        for (Map<String, Object> map : li) {
            Object reapNumber = map.get("reap_number");        //重量
            Object units = map.get("units");            //单位
            if (units != null && reapNumber != null) {
                if (units.toString().equalsIgnoreCase("g")) {
                    BigDecimal divide = new BigDecimal(String.valueOf(reapNumber)).divide(new BigDecimal("1000"));
                    totalNum = totalNum.add(divide);
                }
                if (units.toString().equalsIgnoreCase("kg")) {
                    BigDecimal divide = new BigDecimal(String.valueOf(reapNumber));
                    totalNum = totalNum.add(divide);
                }
                if (units.toString().equalsIgnoreCase("t")) {
                    BigDecimal divide = new BigDecimal(String.valueOf(reapNumber)).multiply(new BigDecimal("1000"));
                    totalNum = totalNum.add(divide);
                }
                if (units.equals("千克")) {
                    BigDecimal divide = new BigDecimal(String.valueOf(reapNumber));
                    totalNum = totalNum.add(divide);
                }
                if (units.equals("克")) {
                    BigDecimal divide = new BigDecimal(String.valueOf(reapNumber)).divide(new BigDecimal("1000"));
                    totalNum = totalNum.add(divide);
                }
                if (units.equals("吨")) {
                    BigDecimal divide = new BigDecimal(String.valueOf(reapNumber)).multiply(new BigDecimal("1000"));
                    totalNum = totalNum.add(divide);
                }
            }
        }
        return totalNum;
    }

}
